import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'
interface ReturnDataType {
  Code: number
  Message: string
  ReturnData: any
}
// process.env.VUE_APP_BASE_API
// create an axios instance
// 开发版本：'http://192.168.22.28:8008/'
// 维思生产管理系统：'http://192.168.18.246:20040/'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true,
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      config.headers!['usertoken'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response: AxiosResponse<ReturnDataType>) => {
    const res = response.data
    if (res.Code === undefined) {
      return response
    }
    // if the custom code is not 20000, it is judged as an error.
    if (res.Code !== 1) {
      Message({
        message: res.Message || '错误',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.Code === 50008 || res.Code === 50012 || res.Code === 50014) {
        // to re-login
        MessageBox.confirm('您已经登出，请返回登录界面', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '离开',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.Message || '错误'))
    } else {
      return response
    }
  },
  error => {
    if (error.response.status === 401) {
      MessageBox.confirm('您未登录或账号过期', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '离开',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          router.push('/login')
        })
      })
      return
    }
    if (error.response.status === 403) {
      MessageBox.confirm('您没有权限登录', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '离开',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          router.push('/login')
        })
      })
      return
    }
    if (error.response.status === 404) {
      router.push('/404')
      return
    }
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
